package top.stmo.stmoBlog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import top.stmo.stmoBlog.dao.pojo.Admin;
import top.stmo.stmoBlog.service.impl.LoginServiceImpl;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private LoginServiceImpl loginService;

    @GetMapping
    public String admin() {
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, String password,
                        HttpSession session, RedirectAttributes attributes, Model model) {
        Admin admin = loginService.login(username,password);
        if(admin == null) {
            attributes.addFlashAttribute("message","用户名或者密码错误");
            return "redirect:/admin";
        }
        admin.setPassword(null);
        session.setAttribute("Attribute",admin);
        model.addAttribute("admin",admin.getUsername());
        return "admin/index";
    }

}
